package com.jiangxiaofei.citycloud.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.UserInfoBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.MainConstant;
import com.jiangxiaofei.citycloud.mvp.MainPersenter;
import com.jiangxiaofei.citycloud.param.UserInfoParam;
import com.jiangxiaofei.citycloud.util.SharedPreferencesUtil;
import com.jiangxiaofei.citycloud.view.IOSAlertDialog;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author JiangXFei
 * 欢迎页面   权限验证页面
 */

public class WelcomeActivity extends BaseActivity
        implements EasyPermissions.PermissionCallbacks,
        MainConstant.UserLoginView {
    @InjectView(R.id.welcome_tv_timer)
    TextView welcomeTvTimer;
    @InjectView(R.id.welcome_tv_in_home)
    TextView welcomeTvInHome;

    private String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private int i;
    private Timer timer;
    private UserInfoParam param = new UserInfoParam();
    private MainConstant.UserLoginPersenter userInfoPersenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        mActivity = this;
        mContext = this;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_welcome_layout);
        ButterKnife.inject(this);
        if (SharedPreferencesUtil.getPrefBoolean(mContext, Constants.FRISTlOGIN, false)) {
        } else {
            SharedPreferencesUtil.setPrefBoolean(mContext, Constants.FRISTlOGIN, true);
        }
        if (EasyPermissions.hasPermissions(this, perms)) {


            initClock();
        } else {
            EasyPermissions.requestPermissions(this, "使用此APP需要提供您以下权限。",
                    200, perms);
        }
        if (SharedPreferencesUtil.getPrefBoolean(mContext, StringConstants.ISLOGIN, false)) {
            param.setName(SharedPreferencesUtil.getPrefString(mContext, StringConstants.NAME, ""));
            param.setPassword(SharedPreferencesUtil.getPrefString(mContext, StringConstants.PASSWORD, ""));
            userInfoPersenter = new MainPersenter(mContext, (MainConstant.UserLoginView) mActivity);
            userInfoPersenter.onLoginUser();
        }
        welcomeTvTimer.setVisibility(View.VISIBLE);
        welcomeTvTimer.setText(3 + StringConstants.SECOND);
    }


    @OnClick({R.id.welcome_tv_in_home})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.welcome_tv_in_home:
                startActivity(new Intent(mContext, HomeActivity.class));
                this.finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 页面加载完成后欢迎页开始计时
     */
    private void initClock() {
        Observable<Integer> obTimer = Observable.create(subscriber -> {
            timer = new Timer();
            i = 3;
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (i < 0) {
                        subscriber.onCompleted();
                    } else if (i >= 0) {
                        subscriber.onNext(i--);
                    }
                }
            };
            timer.schedule(timerTask, 1000, 1000);
        });
        Observer<Integer> observerTimer = new Observer<Integer>() {
            @Override
            public void onCompleted() {
                welcomeTvTimer.setVisibility(View.GONE);
                startActivity(new Intent(mContext, HomeActivity.class));
                mActivity.finish();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(Integer integer) {
                welcomeTvTimer.setText(integer + StringConstants.SECOND);
            }
        };
        obTimer.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observerTimer);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        for (int i = 0; i < perms.size(); i++) {
            if (perms.get(i).equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                initClock();
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        for (int i = 0; i < perms.size(); i++) {
            if (perms.get(i).equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                showDialog();
            }
        }
    }

    public void showDialog() {
        IOSAlertDialog dialog = new IOSAlertDialog(mContext);
        dialog.builder()
                .setTitle("提示")
                .setMsg("使用此软件需要获取到您的位置信息，否则将会影响您的体验！")
                .setPositiveButton("确定", view -> EasyPermissions.requestPermissions(mActivity, "使用此APP需要提供您以下权限。",
                        200, perms))
                .setNegativeButton("取消", view -> mActivity.finish()).show();
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }


    @Override
    public UserInfoParam getUserLoginParam() {
        return param;
    }

    @Override
    public void onLoginSuccess(Object o) {
        List<UserInfoBean> beanList = (List<UserInfoBean>) o;
        if (beanList.size() > 0) {
            UserInfoBean userInfo = beanList.get(0);
            Constants.userInfo = userInfo;
            Constants.userId = Integer.valueOf(userInfo.getId());
        }
    }
}
